package com.edfeff.bio.http;


import java.util.ArrayList;
import java.util.List;

public class Response {
    protected int status = 200;
    protected String message = null;
    private List<Header> headers = new ArrayList<>();
    private byte[] body;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * <pre>
     *     response-header = Accept-Ranges           ; Section 14.5
     *                        | Age                     ; Section 14.6
     *                        | ETag                    ; Section 14.19
     *                        | Location                ; Section 14.30
     *                        | Proxy-Authenticate      ; Section 14.33
     *                        | Retry-After             ; Section 14.37
     *                        | Server                  ; Section 14.38
     *                        | Vary                    ; Section 14.44
     *                        | WWW-Authenticate        ; Section 14.47
     * </pre>
     *
     * @return
     */
    public List<Header> getHeaders() {
        return headers;
    }

    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    public byte[] getBody() {
        return body;
    }

    public void setContentType(String contentType) {
        Header header = getHeader("content-type");
        if (header == null) {
            headers.add(new Header("content-type", contentType));
        } else {
            header.setValue(contentType);
        }
    }

    public void setStringBody(String body) {
        setBody(body.getBytes(Constants.charset));
    }

    public void setBody(byte[] body) {
        if (body == null || body.length == 0)
            return;
        //修改响应头 content-length
        Header header = getHeader("content-length");
        if (header == null) {
            headers.add(new Header("content-length", "" + body.length));
        } else {
            header.setValue("" + body.length);
        }
        this.body = body;
    }

    public Header getHeader(String headerName) {
        //todo 哈希优化
        for (Header header : headers) {
            if (headerName.equals(header.getName()))
                return header;

        }
        return null;
    }
}
